/**
 * DISCLAIMER
 * 
 * The quality of the code is such that you should not copy any of it as best
 * practice how to build Vaadin applications.
 * 
 * @author jouni@vaadin.com
 * 
 */

package com.vaadin.demo.dashboard;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.quick.bean.Userprofile;
import com.quick.global.GlobalConstants;
import com.quick.global.GlobalNotifications;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.quick.data.DataProvider;
import com.quick.data.MyConverterFactory;
import com.quick.dictionary.DictView;
import com.quick.forum.ForumView;
import com.quick.notices.CreateNotices;
import com.quick.planner.PlannerView;
import com.quick.ui.exam.AdminExam;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.event.ShortcutListener;
import com.vaadin.navigator.Navigator;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.server.Page;
import com.vaadin.server.ThemeResource;
import com.vaadin.server.VaadinRequest;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.DragAndDropWrapper;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Image;
import com.vaadin.ui.Label;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Table;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import java.lang.reflect.Type;
import java.util.*;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

@Theme("dashboard")
@Title("Rahul Karad")
public class DashboardUI extends UI{

    DataProvider dataProvider = new DataProvider();

    private static final long serialVersionUID = 1L;

    CssLayout rootCSS = new CssLayout();
    VerticalLayout loginLayout;
    HorizontalLayout menuCSS = new HorizontalLayout();
    CssLayout contentCSS = new CssLayout();
    HashMap<String, Button> viewNameToMenuButton = new HashMap<String, Button>();
    private Navigator nav;
    private static final String rootStyleName="root";
    private static final String loginBgStyleName="login-bg";

    HashMap<String, Class<? extends View>> routesMap = new HashMap<String, Class<? extends View>>() {
        {
            put(GlobalConstants.ROUT_HOME, HomeView.class);
            put(GlobalConstants.ROUT_ABOUT, AboutView.class);
            put(GlobalConstants.ROUT_LEADERSHIP,LeadershipView.class);
            put(GlobalConstants.ROUT_ACHIEVEMENTS,AchievementsView.class);            
            put(GlobalConstants.ROUT_NOTICES,CreateNotices.class);
            put(GlobalConstants.ROUT_FORUM,ForumView.class);
            put(GlobalConstants.ROUT_GALLERY,GalleryView.class);
            put(GlobalConstants.ROUT_PLANNER,PlannerView.class);
            
            //put(GlobalConstants.ROUT_GALLERY,PlayView.class);
            put(GlobalConstants.ROUT_CONNECT, ConnectView.class);
            put(GlobalConstants.ROUT_TOPICS,QuickUpload.class);            
            put(GlobalConstants.ROUT_EXAM_ADMIN,AdminExam.class);
            put(GlobalConstants.ROUT_STUDENTS,StudentView.class);
            put(GlobalConstants.ROUT_TEACHERS,TeacherView.class);
            put(GlobalConstants.ROUT_DICT,DictView.class);            
        }
    };

    
    @Override
    protected void init(VaadinRequest request) {
        getSession().setConverterFactory(new MyConverterFactory());
        setLocale(Locale.US);
        
        
        Panel rootPanel = new Panel();
        rootPanel.setWidth("100%");
        //rootPanel.setHeight("100%");
        rootPanel.setContent(rootCSS);
        
        setContent(rootPanel);
        
        rootCSS.addStyleName(rootStyleName);
        //rootCSS.setSizeFull();
        rootCSS.setWidth("100%");
        rootCSS.addStyleName("profile_style_picture_bg");
        
        // Unfortunate to use an actual widget here, but since CSS generated
        // elements can't be transitioned yet, we must
//        Label bg = new Label();
//        bg.setSizeUndefined();
//        bg.addStyleName(loginBgStyleName);
//        rootCSS.addComponent(bg);
        
        loginLayout = new VerticalLayout();
        loginLayout.setSizeFull();
        loginLayout.addStyleName(loginLayoutStyle);
        loginLayout.setSpacing(false);
        loginLayout.setMargin(true);
        
//rootCSS.addComponent(loginLayout);       
        //addHeadingLabels();
        //buildLoginView(false);
        
        buildMainView();

    }

    private static final String loginStyle="login";
    private static final String loginLayoutStyle="login-layout";
    private static final String loginPanelStyle="login-panel";
    private static final String lablesStyle="labels";
    private static final String lableWelcome="Welcome";
    private static final String h4Style="h4";
    private static final String h2Style="h2";
    private static final String lableTitaliDashboard=GlobalConstants.getProperty(GlobalConstants.PRODUCT_NAME);
    private static final String lightStyle="light";
    private static final String fieldsStyle="fields";
    private static final String strUsername="Email";
    private static final String strPassword="Password";
    private static final String strSignIn="Enter site";
    private static final String errorStyle="error";
    private static final String strWrongCredentials="Wrong username or password.";
    private static final String vAnimateRevealStyle="v-animate-reveal";
    private static final String defaultStyle="default";
    
     private void buildLoginView(boolean exit) {
        if (exit) {
            rootCSS.removeAllComponents();
        }
        

        
        final Button signin = new Button(strSignIn);
        signin.addStyleName(defaultStyle);
        
        HorizontalLayout loginAndSignup = new HorizontalLayout();
        loginAndSignup.setSpacing(true);
        loginAndSignup.setWidth("100%");
        loginAndSignup.addComponent(signin);
        loginAndSignup.setExpandRatio(signin, 1.5f);
        loginAndSignup.setComponentAlignment(signin, Alignment.BOTTOM_RIGHT);
        loginLayout.addComponent(loginAndSignup);

        final ShortcutListener enter = new ShortcutListener(strSignIn,
                KeyCode.ENTER, null) {
            @Override
            public void handleAction(Object sender, Object target) {
                signin.click();
            }
        };

         signin.addClickListener(new ClickListener() {
             @Override
             public void buttonClick(ClickEvent event) {

                 signin.removeShortcutListener(enter);
                 buildMainView();
                 //getSession().setAttribute(userName,username.getValue());
             }
         });

         signin.addShortcutListener(enter);

        
    }
     
     
     private static final String brandingStyle="branding";
     private static final String sidebarStyle="sidebar";
     private static final String userStyle="user";
     private static final String sweetOrangeBg="sweetOrangeBg";

    private void buildMainView() {

        nav = new Navigator(this, contentCSS);

        for (String route : routesMap.keySet()) {
            nav.addView(route, routesMap.get(route));
        }

        
        removeStyleName(loginStyle);
        rootCSS.removeComponent(loginLayout);
        
        VerticalLayout mainVertical = new VerticalLayout() {
            {
                //setSizeFull();
                //addStyleName("main-view");
                addStyleName("mainVerticalStyle");
                addStyleName("transparentBg");
                setSpacing(true);
                
                setWidth("72%");
                //setHeight("130%");  
                //F4C611
                //Label nameHeading = new Label("<div style='color:#F16E50;display:inline-block;font-size:35px;'>RAHUL<b>KARAD</b></div>",ContentMode.HTML);
                Image promoImage = new Image(null, new ThemeResource("img/promo-image.jpg"));
                promoImage.setSizeFull();

//                HorizontalLayout nameLayout = new HorizontalLayout();
//                nameLayout.setSizeFull();
//                nameLayout.setWidth("100%");
//                nameLayout.setHeight("80%");
//                nameLayout.addStyleName("promoImageBg");
//                nameLayout.addComponent(promoImage);
//                nameLayout.setMargin(false);
                
                addComponent(promoImage);
                setExpandRatio(promoImage, 1.8f);
                
                
                HorizontalLayout menuLayout = new HorizontalLayout() {
                    // Sidebar
                    {
                        addStyleName(sidebarStyle);
                        addStyleName("floatingStyle");
                        addStyleName("saffronBg");
                        setMargin(false);
                        setSpacing(false);
                        
                        setWidth("100%");
                        setHeight("100%");
                        
                        addComponent(menuCSS);
                    }
                };
                
                addComponent(menuLayout);
                setExpandRatio(menuLayout, 0.30f);
                //setComponentAlignment(menuLayout, Alignment.BOTTOM_CENTER);
                // Content
                contentCSS.setSizeFull();
                contentCSS.addStyleName("view-content");
                addComponent(contentCSS);
                setExpandRatio(contentCSS, 3.5f);
            }

        };
        

        rootCSS.addComponent(mainVertical);
        //rootCSS.setComponent(mainVertical);

        menuCSS.removeAllComponents();
 
        String[]  actionsList;
//               actions= new String[] { "dashboard", "learn","Technology","Exams","Notices","Forum","reports",
//            "upload","Exam-Admin","students","teachers" };
        //actionsList= new String[] { "home","about", "leadership","achievements","news","testimonials","gallery","planner","blog","connect"};
        actionsList= new String[] { "home","about", "leadership","achievements","BCS","news","testimonials","photo-gallery","planner","connect"};
        
        
        for (final String action : actionsList) {
            
            Button b = new NativeButton(action.substring(0, 1).toUpperCase()+ action.substring(1).replace('-', ' '));
            b.addStyleName("whiteBg");
            b.addClickListener(new ClickListener() {
                @Override
                public void buttonClick(ClickEvent event) {
                    clearMenuSelection();
                    event.getButton().addStyleName("selected");
                    if (!nav.getState().equals("/" + action))
                        nav.navigateTo("/" + action);
                }
            });

            
            menuCSS.addComponent(b);
            viewNameToMenuButton.put("/" + action, b);
        }
        
        
        menuCSS.addStyleName("menu");
       // menuCSS.addStyleName("leachBg");
       // menuCSS.setHeight("100%");

        viewNameToMenuButton.get(GlobalConstants.ROUT_HOME).setHtmlContentAllowed(true);
        //viewNameToMenuButton.get(GlobalConstants.ROUT_HOME).setCaption("Home<span class=\"badge\">5</span>");

        String f = Page.getCurrent().getUriFragment();
        if (f != null && f.startsWith("!")) {
            f = f.substring(1);
        }
        if (f == null || f.equals("") || f.equals("/")) {
            nav.navigateTo(GlobalConstants.ROUT_HOME);
            menuCSS.getComponent(0).addStyleName("selected");
            
        } else {
            if(!f.equals(GlobalConstants.emptyString))
            {
            nav.navigateTo(f);
            
            viewNameToMenuButton.get(f).addStyleName("selected");
            }
        }

        nav.addViewChangeListener(new ViewChangeListener() {

            @Override
            public boolean beforeViewChange(ViewChangeListener.ViewChangeEvent event) {
                
                return true;
            }

            @Override
            public void afterViewChange(ViewChangeListener.ViewChangeEvent event) {
                View newView = event.getNewView();
                
                if (autoCreateReport && newView instanceof ReportsView) {
                    //((ReportsView) newView).autoCreate(2, items, transactions);
                }
                autoCreateReport = false;
            }
        });

    }

    

    private void clearMenuSelection() {
        for (Iterator<Component> it = menuCSS.getComponentIterator(); it.hasNext();) {
            Component next = it.next();
            if (next instanceof NativeButton) {
                next.removeStyleName("selected");
            } else if (next instanceof DragAndDropWrapper) {
                // Wow, this is ugly (even uglier than the rest of the code)
                ((DragAndDropWrapper) next).iterator().next()
                        .removeStyleName("selected");
            }
        }
    }

    void updateReportsButtonBadge(String badgeCount) {
        viewNameToMenuButton.get(GlobalConstants.ROUT_CONNECT).setHtmlContentAllowed(true);
        viewNameToMenuButton.get(GlobalConstants.ROUT_CONNECT).setCaption(
                "Reports<span class=\"badge\">" + badgeCount + "</span>");
    }

    void clearDashboardButtonBadge() {
        viewNameToMenuButton.get(GlobalConstants.ROUT_HOME).setCaption("Dashboard");
    }

    boolean autoCreateReport = false;
    Table transactions;

    public void openReports(Table t) {
        transactions = t;
        autoCreateReport = true;
        nav.navigateTo(GlobalConstants.ROUT_CONNECT);
        clearMenuSelection();
        viewNameToMenuButton.get(GlobalConstants.ROUT_CONNECT).addStyleName("selected");
    }

    
    
    private static final String userName="userName";
    private static final String strPwd="password";
    private boolean isValidUser(String username, String pwd) {
        
        boolean isvaliduser = false;
        try {
            Client client = Client.create();
            WebResource webResource = client.resource(GlobalConstants.getProperty(GlobalConstants.LOGIN_URL));
            //String input = "{\"userName\":\"raj\",\"password\":\"FadeToBlack\"}";
            JSONObject inputJson = new JSONObject();
            try {
                inputJson.put(userName, username.trim());
                inputJson.put(strPwd, pwd.trim());
            } catch (JSONException ex) {
                ex.printStackTrace();
            }


            ClientResponse response = webResource.type("application/json").post(ClientResponse.class, inputJson);

            /*
             * if (response.getStatus() != 201) { throw new
             * RuntimeException("Failed : HTTP error code : " +
             * response.getStatus()); }
             */

            String output = response.getEntity(String.class);
            System.out.println("output=" + output);


            JSONObject response1 = null;

            response1 = new JSONObject(output);

            if (response1.get(GlobalConstants.isAuthenticated).equals(GlobalConstants.YES)) {
                isvaliduser = true;
                Type listType = new TypeToken<ArrayList<Userprofile>>() {}.getType();
                List<Userprofile> list =new Gson().fromJson(response1.getString(GlobalConstants.CurrentUserProfile), listType);
                loggedinProfile=list.get(0);
                
                userRole=response1.getString(GlobalConstants.role);
                loggedinProfile.setRole(userRole);
                
                getSession().setAttribute(GlobalConstants.CurrentUserProfile,loggedinProfile);
                
            } else {
                 Notification.show(GlobalNotifications.INVALID_CREDENTIALS);
            }
        } catch (JSONException ex) {
            ex.printStackTrace();
          
        }
        
           return isvaliduser;
    }
    
    private Userprofile loggedinProfile;
    private String userRole;

    private VerticalLayout addHeadingLabels() 
    {
        VerticalLayout headings = new VerticalLayout();
        headings.setSpacing(true);
        
        Label productName = new Label("\"The Bharatiya Chhatra Sansad (Indian Student Parliament) "
                + "envisages that motivated, committed and political youth leaders"
                + " will emerge to provide a positive and effective "
                + "leadership to their country and practice morality and politics for "
                + "the betterment of the country and the world\""
                + "<br><br> "
                + " <div class=\"img-circular\"></div>"+"&nbsp;-&nbsp;"+GlobalConstants.getProperty(GlobalConstants.PRODUCT_NAME).toUpperCase(),ContentMode.HTML);
        productName.addStyleName("login-product-label");
        
//        Label signIn = new Label("Sign in to continue to dashboard",ContentMode.HTML);
//        signIn.addStyleName("sign-in-tocontinue");
        
        headings.addComponent(productName);
        headings.setComponentAlignment(productName, Alignment.MIDDLE_CENTER);
        //
        //headings.addComponent(UIUtils.getSchoolBannerLayout());
//        headings.addComponent(signIn);
//        headings.setComponentAlignment(signIn, Alignment.MIDDLE_CENTER);
        
        loginLayout.addComponent(headings);
        loginLayout.setComponentAlignment(headings, Alignment.MIDDLE_CENTER);
        loginLayout.setExpandRatio(headings,1);
        
        return headings;
        
    }
}